package com.practice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import com.aiyige.MyApp;
import com.aiyige.page.my.MyPage;
import com.netease.nim.uikit.common.util.sys.TimeUtil;

public class EchoServerService extends Service {
    public static final int SERVER_PORT = 8080;
    public static final String ACTION_START_SERVER = "stb.ACTION_START_SERVER";
    public static final String ACTION_STOP_SERVER = "stb.ACTION_STOP_SERVER";
    ServerThread serverThread;


    public EchoServerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public void onCreate() {
        super.onCreate();
        serverThread = null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action;
        try {
            action = intent.getAction();
            action = TextUtils.isEmpty(action) ? ACTION_START_SERVER : action;
        } catch (Exception e) {
            action = ACTION_START_SERVER;
        }
        switch (action) {
            case ACTION_START_SERVER: {
                if (serverThread == null) {
                    serverThread = new ServerThread();
                    serverThread.start();
                }
                return Service.START_STICKY;
            }
            case ACTION_STOP_SERVER: {
                stopSelf();
                return Service.START_NOT_STICKY;
            }
            default: {
                return Service.START_STICKY;
            }
        }
    }

    @Override
    public void onDestroy() {
        if (serverThread != null) {
            serverThread.shutdown();
        }
        super.onDestroy();
    }


    class ServerThread extends Thread {
        EchoServer echoServer;

        @Override
        public void run() {
            echoServer = new EchoServer();
            echoServer.startServer(SERVER_PORT);
        }

        public void shutdown() {
            echoServer.stopServer();
            try {
                join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void startService() {
        Intent intent = new Intent(MyApp.getAppContext(), EchoServerService.class);
        intent.setAction(ACTION_START_SERVER);
        MyApp.getAppContext().startService(intent);
    }

    public static void stopService() {
        Intent intent = new Intent(MyApp.getAppContext(), EchoServerService.class);
        intent.setAction(ACTION_STOP_SERVER);
        MyApp.getAppContext().startService(intent);
    }


}
